package com.leyou.common.upload;


import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * @author:yanjizhw@163.com
 * @date:2019/10/1 8:38
 * 描述: 文件上传
 * @since:1.0.0
 */
public class Upload {

    public static String fileUpload(MultipartFile image){

        String file = "";

        //1、把图片放入服务器
        if (image != null){

            String fileName = image.getOriginalFilename();

            // 1.1 校验图片大小(在配置文件中)

            // 1.2 校验图片格式
            try {

                Image isImage = ImageIO.read(image.getInputStream());

                if (isImage == null || isImage.getWidth(null) <= 0 || isImage.getHeight(null) <= 0){
                    throw new LyException(ExceptionEnum.INVALID_FILE_FORMAT);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            // 1.3 准备目标路径
            File dest = new File("D:\\data\\javadata\\idea\\yun6\\image\\", fileName);

            file = "/path/" + fileName;

            try {
                // 1.4 保存到本地路径
                image.transferTo(dest);

            } catch (IOException e) {
                // 上传失败
                throw new LyException(ExceptionEnum.UPLOAD_IMAGE_EXCEPTION);
            }
        }

        return file;

    }
}
